package com.jiezuo.auth.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.google.common.collect.Lists;
import com.jiezuo.auth.entity.Enterprise;
import com.jiezuo.auth.service.EnterpriseService;
import com.jiezuo.common.annotation.RepeatSubmit;
import com.jiezuo.common.base.BaseController;
import com.jiezuo.common.enums.ResultEnums;
import com.jiezuo.common.util.*;
import com.jiezuo.common.vo.PageVo;
import com.jiezuo.common.vo.Result;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * @description 企业管理
 * @author 庞留杰
 * @date 2020/08/26 14:37
 * @version V1.0
 **/
@Slf4j
@Transactional
@RequestMapping("/enterprise")
@RestController
//企业管理", tags = {"企业管理接口"})
public class EnterpriseController extends BaseController {

    @Autowired
    private EnterpriseService service;

    //查询带分页列表", notes = "查询带分页列表")
    @GetMapping("/findPage")
    public Result<IPage<Enterprise>> findPage(@ModelAttribute PageVo pageVo, @ModelAttribute Enterprise enterprise) {
        IPage<Enterprise> page = service.findPage(PageUtil.initMpPage(pageVo), enterprise);
        return new ResultUtil<IPage<Enterprise>>().setData(page);
    }

    //查询不带分页列表", notes = "查询不带分页列表")
    @GetMapping("/findList")
    public Result<List<Enterprise>> findList(@ModelAttribute Enterprise enterprise) {
        List<Enterprise> list = service.findList(enterprise);
        return new ResultUtil<List<Enterprise>>().setData(list);
    }

    //通过ID查询", notes = "通过ID查询")
    @GetMapping("/findById")
    public Result<Enterprise> findById(String id) {
        Enterprise enterprise = service.findById(id);
        return new ResultUtil<Enterprise>().setData(enterprise);
    }

    @RepeatSubmit
    //添加", notes = "添加")
    @PostMapping("/save")
    public Result save(@RequestBody Enterprise enterprise) {
        VerifyUtil.notEmpty("上级企业",enterprise.getPid());
        service.save(enterprise);
        if("0".equals(enterprise.getPid())){
            enterprise.setAncestors(enterprise.getPid()+","+enterprise.getId());
        }else {
            Enterprise e = service.getById(enterprise.getPid());
            enterprise.setAncestors(e.getAncestors()+","+enterprise.getId());
        }
        boolean boo = service.updateById(enterprise);
        if (boo) {
            return new ResultUtil().setSuccessMsg(ResultEnums.OK.getReasonPhraseCN());
        } else {
            return new ResultUtil().setErrorMsg(ResultEnums.FAIL.getReasonPhraseCN());
        }
    }

    //修改", notes = "修改")
    @PostMapping("/update")
    public Result update(@RequestBody Enterprise enterprise) {
        VerifyUtil.notEmpty("上级企业",enterprise.getPid());
        List<Enterprise> list = service.list();
        String ids = "";
        //自己的父id不能与自己相同
        if(enterprise.getId().equals(enterprise.getPid())){
            return new ResultUtil().setErrorMsg("上级企业不能选择自己");
        }
        //所有子级ID
        String allChildrenIds = allChildren(list, ids, enterprise.getId());
        String[] arr = allChildrenIds.split(",");
        //自己不能添加到自己的子级
        if(Arrays.asList(arr).contains(enterprise.getPid())){
            return new ResultUtil().setErrorMsg("上级企业不能选择自己的子级企业");
        }

        if("0".equals(enterprise.getPid())){
            enterprise.setAncestors(enterprise.getPid()+","+enterprise.getId());
        }else {
            Enterprise e = service.getById(enterprise.getPid());
            enterprise.setAncestors(e.getAncestors()+","+enterprise.getId());
        }
        boolean boo = service.updateById(enterprise);
        if (boo) {
            return new ResultUtil().setSuccessMsg(ResultEnums.OK.getReasonPhraseCN());
        } else {
            return new ResultUtil().setErrorMsg(ResultEnums.FAIL.getReasonPhraseCN());
        }
    }

    //查询所有子级的父ID
    public String allChildren(List<Enterprise> list,String ids,String id) {
        if(isNotChildren(list,id)){
            for (Enterprise enterprise : list) {
                if(id.equals(enterprise.getPid())){
                    ids = allChildren(list,ids,enterprise.getId());
                    ids += enterprise.getId()+",";
                }
            }
        }
        return ids;
    }

    //判断是否还有子级
    public boolean isNotChildren(List<Enterprise> list,String id) {
        boolean boo = false;
        for (Enterprise enterprise : list) {
            if(id.equals(enterprise.getPid())){
                boo = true;
                break;
            }
        }
        return boo;
    }

    //删除", notes = "删除【逻辑删除】")
    @PostMapping("/delete/{id}")
    public Result delete(@PathVariable String id) {
        Enterprise enterprise = new Enterprise();
        enterprise.setId(id);
        enterprise.setIs_delete("1");
        boolean boo = service.updateById(enterprise);
        if (boo) {
            return new ResultUtil().setSuccessMsg(ResultEnums.OK.getReasonPhraseCN());
        } else {
            return new ResultUtil().setErrorMsg(ResultEnums.FAIL.getReasonPhraseCN());
        }
    }

    //批量删除", notes = "批量删除")
    //(name = "ids", value = "格式:[1,2,3]", dataType = "Array", required = true, paramType = "body")
    @PostMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody String[] ids) {
        List<Enterprise> list = Lists.newArrayList();
        for(String id:ids){
            Enterprise enterprise = service.getById(id);
            if(enterprise != null){
                enterprise.setIs_delete("1");
                list.add(enterprise);
            }
        }
        if(list.size()>0){
            service.updateBatchById(list);
        }
        return new ResultUtil().setSuccessMsg(ResultEnums.OK.getCode());
    }

    //企业树", notes = "企业树")
    @GetMapping("/enterpriseTree")
    public Result<List<Enterprise>> enterpriseTree(@ModelAttribute Enterprise enterprise) {
        List<Enterprise> enterprises = service.enterpriseTree(enterprise);
        return new ResultUtil().setData(enterprises);
    }

    //企业树部门树", notes = "企业树部门树")
    @GetMapping("/enterpriseDepartTree")
    public Result<JSONArray> enterpriseDepartTree() {
        JSONArray enterprisesDepart = service.enterpriseDepartTree();
        return new ResultUtil().setData(enterprisesDepart);
    }

}
